import datetime

import wx

from common.event_dispatcher import EventDispatcher


class LogPanel(wx.Panel):
    def __init__(self, parent):
        super(LogPanel, self).__init__(parent)

        # 日志文本框
        self.log_ctrl = wx.TextCtrl(
            self,
            style=wx.TE_MULTILINE | wx.TE_READONLY | wx.HSCROLL | wx.TE_RICH2
        )
        self.log_ctrl.SetFont(wx.Font(10, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))

        # 控制按钮
        btn_clear = wx.Button(self, label="清空日志")
        btn_save = wx.Button(self, label="保存日志")

        # 布局
        btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
        btn_sizer.Add(btn_clear, 0, wx.RIGHT, 5)
        btn_sizer.Add(btn_save, 0)

        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(self.log_ctrl, 1, wx.EXPAND)
        main_sizer.Add(btn_sizer, 0, wx.ALIGN_RIGHT | wx.ALL, 5)

        self.SetSizer(main_sizer)

        # 事件绑定
        btn_clear.Bind(wx.EVT_BUTTON, self.on_clear)
        btn_save.Bind(wx.EVT_BUTTON, self.on_save)



    def handle_log(self, data):
        print('data', data)
        """添加日志消息"""
        id = data.get('id', -1)
        if id == 0:
            message = data.get('message')
        else:
            return
        # 实际业务处理逻辑
        self.log_ctrl.AppendText(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} {message}\n")

        #self.log_ctrl.AppendText(f"{message}\n")
        self.log_ctrl.ScrollLines(1)


    def log_message(self, data):
        print('data',data)
        """添加日志消息"""
        id = data.get('id',-1)
        if id == 0:
            message = data.get('message')
        else:
            return
        self.log_ctrl.AppendText(f"{message}\n")
        self.log_ctrl.ScrollLines(1)

    def on_clear(self, event):
        """清空日志"""
        self.log_ctrl.Clear()

    def on_save(self, event):
        """保存日志到文件"""
        with wx.FileDialog(self, "保存日志文件", wildcard="日志文件 (*.log)|*.log",
                           style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as dlg:
            if dlg.ShowModal() == wx.ID_OK:
                try:
                    with open(dlg.GetPath(), 'w', encoding='utf-8') as f:
                        f.write(self.log_ctrl.GetValue())
                    self.log_message(f"日志已保存到: {dlg.GetPath()}")
                except Exception as e:
                    wx.MessageBox(f"保存失败: {str(e)}", "错误", wx.OK | wx.ICON_ERROR)